﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Input.Touch;

namespace BandStandWoodblock
{
    /// <summary>
    /// Implements IServiceProvider for the application. This type is exposed through the App.Services
    /// property and can be used for ContentManagers or other types that need access to an IServiceProvider.
    /// </summary>
    public class AppServiceProvider : IServiceProvider
    {
        // A map of service type to the services themselves
        private readonly Dictionary<Type, object> services = new Dictionary<Type, object>();

        /// <summary>
        /// Adds a new service to the service provider.
        /// </summary>
        /// <param name="serviceType">The type of service to add.</param>
        /// <param name="service">The service object itself.</param>
        public void AddService(Type serviceType, object service)
        {
            // Validate the input
            if (serviceType == null)
                throw new ArgumentNullException("serviceType");
            if (service == null)
                throw new ArgumentNullException("service");
            if (!serviceType.IsAssignableFrom(service.GetType()))
                throw new ArgumentException("service does not match the specified serviceType");

            // Add the service to the dictionary
            services.Add(serviceType, service);
        }

        /// <summary>
        /// Gets a service from the service provider.
        /// </summary>
        /// <param name="serviceType">The type of service to retrieve.</param>
        /// <returns>The service object registered for the specified type..</returns>
        public object GetService(Type serviceType)
        {
            // Validate the input
            if (serviceType == null)
                throw new ArgumentNullException("serviceType");

            // Retrieve the service from the dictionary
            return services[serviceType];
        }

        /// <summary>
        /// Removes a service from the service provider.
        /// </summary>
        /// <param name="serviceType">The type of service to remove.</param>
        public void RemoveService(Type serviceType)
        {
            // Validate the input
            if (serviceType == null)
                throw new ArgumentNullException("serviceType");

            // Remove the service from the dictionary
            services.Remove(serviceType);
        }
    }

    public partial class GamePage : PhoneApplicationPage
    {
        ContentManager contentManager;
        GameTimer timer;
        SpriteBatch spriteBatch;

        UIElementRenderer elementRenderer;

        Texture2D bg;
        Texture2D stick;

        SoundEffect[] effects;
        Rectangle[] blocks;

        float halfstep = 1 / 12f;

        public GamePage()
        {
            InitializeComponent();

            // Get the content manager from the application
            contentManager = (Application.Current as BandStand.App).Content;

            // Create a timer for this page
            timer = new GameTimer();
            timer.UpdateInterval = TimeSpan.FromTicks(333333);
            timer.Update += OnUpdate;
            timer.Draw += OnDraw;

            LayoutUpdated += new EventHandler(XNARendering_LayoutUpdated);

            instances = new List<SoundEffectInstance>();
        }

        void XNARendering_LayoutUpdated(object sender, EventArgs e)
        {
            // make sure page size is valid
            if (ActualWidth == 0 || ActualHeight == 0)
                return;

            // see if we already have the right sized renderer
            if (elementRenderer != null &&
                elementRenderer.Texture != null &&
                elementRenderer.Texture.Width == (int)ActualWidth &&
                elementRenderer.Texture.Height == (int)ActualHeight)
            {
                return;
            }

            // dispose the current renderer
            if (elementRenderer != null)
                elementRenderer.Dispose();

            // create the renderer
            elementRenderer = new UIElementRenderer(this, (int)ActualWidth, (int)ActualHeight);
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            // Set the sharing mode of the graphics device to turn on XNA rendering
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(true);

            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(SharedGraphicsDeviceManager.Current.GraphicsDevice);

            effects = new SoundEffect[3];
            effects[0] = contentManager.Load<SoundEffect>("c4");
            effects[1] = contentManager.Load<SoundEffect>("c5");
            effects[2] = contentManager.Load<SoundEffect>("c6");

            blocks = new Rectangle[3];
            blocks[0] = new Rectangle(64, 62, 350, 200);
            blocks[1] = new Rectangle(65, 262, 350, 200);
            blocks[2] = new Rectangle(65, 462, 350, 200);

            bg = contentManager.Load<Texture2D>("bg");
            stick = contentManager.Load<Texture2D>("stick");

            ThunderFish.TAccelerometer.Initialize();

            // Start the timer
            timer.Start();

            base.OnNavigatedTo(e);
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            // Stop the timer
            timer.Stop();

            // Set the sharing mode of the graphics device to turn off XNA rendering
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(false);

            ThunderFish.TAccelerometer.Deinitialize();

            base.OnNavigatedFrom(e);
        }

        /// <summary>
        /// Allows the page to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        private void OnUpdate(object sender, GameTimerEventArgs e)
        {
            foreach (TouchLocation t in TouchPanel.GetState())
            {
                if (t.State == TouchLocationState.Pressed)
                {
                    for (int c = 0; c < blocks.Length; c++)
                    {
                        if (blocks[c].Contains(
                            new Microsoft.Xna.Framework.Point((int)t.Position.X, (int)t.Position.Y)))
                        {
                            lastBlock = c;
                            stickAnimCur = stickAnimLen;
                            PlaySound(effects[c],
                                (int)(Math.Abs(ThunderFish.TAccelerometer.Reading.Y) * 12) * halfstep);
                        }
                    }
                }
            }

            stickAnimCur -= e.ElapsedTime;
            if (stickAnimCur <= TimeSpan.Zero) stickAnimCur = TimeSpan.Zero;

            for (int c = instances.Count - 1; c >= 0; c--)
                if (instances[c].State == SoundState.Stopped) instances.RemoveAt(c);
        }

        List<SoundEffectInstance> instances;

        private void PlaySound(SoundEffect sound, float pitch)
        {
            pitch = Math.Min(pitch, 1.0f);
            pitch = Math.Max(pitch, -1.0f);

            SoundEffectInstance inst = sound.CreateInstance();
            inst.Pitch = pitch;
            inst.Play();
            instances.Add(inst);
        }

        TimeSpan stickAnimLen = new TimeSpan(0, 0, 0, 0, 50);
        TimeSpan stickAnimCur;
        int lastBlock = 0;

        /// <summary>
        /// Allows the page to draw itself.
        /// </summary>
        private void OnDraw(object sender, GameTimerEventArgs e)
        {
            SharedGraphicsDeviceManager.Current.GraphicsDevice.Clear(Color.CornflowerBlue);

            elementRenderer.Render();

            spriteBatch.Begin();
            spriteBatch.Draw(bg, Vector2.Zero, Color.White);
            if (lastBlock >= 0)
            {
                spriteBatch.Draw(
                    stick,
                    new Vector2(blocks[lastBlock].Center.X, blocks[lastBlock].Center.Y) - new Vector2(0, 577)
                     + new Vector2(ThunderFish.TAccelerometer.Reading.Y * 100, 0),
                    null,
                    Color.White,
                    (float)Math.PI / 4 + (float)Math.PI / 4 * (1 - (float)(stickAnimCur.TotalMilliseconds / stickAnimLen.TotalMilliseconds)),
                    new Vector2(11, 81),
                    Vector2.One,
                    SpriteEffects.None,
                    1.0f);
            }
            spriteBatch.Draw(elementRenderer.Texture, Vector2.Zero, Color.White);
            spriteBatch.End();
        }
    }
}